﻿using System;
using System.Windows.Forms;
using System.Collections.ObjectModel;

namespace PSSymbolStore.Manager.Windows
{
    public partial class DynamicPrompt : Form
    {
        public DynamicPrompt()
        {
            InitializeComponent();

            SelectedChoice = -1;
        }

        public string Caption
        {
            get
            {
                return Text;
            }
            set
            {
                Text = value;
            }
        }

        public string Message
        {
            get
            {
                return labelMessage.Text;
            }
            set
            {
                labelMessage.Text = value;
            }
        }

        public int SelectedChoice { get; set; }

        public void SetChoices(Collection<ChoiceDescription> choices, int defaultChoice)
        {
            choiceToolTip.RemoveAll();
            foreach (Button b in choiceContainerPanel.Controls)
            {
                b.Click -= OnChoiceClick;
            }
            choiceContainerPanel.Controls.Clear();

            if (choices != null)
            {
                Button defaultButton = null;
                // Reverse iterate to get the buttons to show in the correct order
                for (int i = choices.Count-1; i >= 0; i--)
                {
                    Button b = AddChoice(choices[i], i);
                    if (i == defaultChoice)
                    {
                        defaultButton = b;
                    }
                }

                AcceptButton = defaultButton;
                ActiveControl = defaultButton;
            }

            if (choiceContainerPanel.Controls.Count > 0)
            {
                // There are choice buttons which will dismiss the form (expected)
                // so we can hide the "X" button (meaning they have to choose something)
                ControlBox = false;
            }
        }

        private Button AddChoice(ChoiceDescription choiceDescription, int i)
        {
            var b = new Button
                        {
                            AutoSizeMode = AutoSizeMode.GrowAndShrink,
                            AutoSize = true,
                            Text = choiceDescription.Label,
                            DialogResult = DialogResult.OK,
                            Tag = i
                        };

            b.Click += OnChoiceClick;
            choiceToolTip.SetToolTip(b, choiceDescription.HelpMessage);
            choiceContainerPanel.Controls.Add(b);

            return b;
        }

        void OnChoiceClick(object sender, EventArgs e)
        {
            var b = (Button)sender;
            SelectedChoice = (int)b.Tag;
            DialogResult = DialogResult.OK;
        }
    }
}
